import threading
import websockets
import time
import sys
import os
import numpy as np
from queue import Queue
import cv2
from socket import *
import asyncio


sock = socket(AF_INET, SOCK_DGRAM)  # 创建UDP套接字
Host = '192.168.3.16'
Port = 5555
ws_port = 5766
sock.bind((Host, Port))
# sock.setblocking(0)  # 设置为非阻塞模式

USERS = []
q = Queue(50)


def restart_program():
    python = sys.executable
    os.execl(python, python, *sys.argv)


def revecive():
    while True:
        global data
        try:
            data, address = sock.recvfrom(921600)
            if len(USERS) > 0 and q.empty():
                q.put(data)
            receive_data = np.frombuffer(data, dtype='uint8')
            frame = cv2.imdecode(receive_data, 1)
            cv2.imshow('server', frame)
            data = cv2.imencode('.jpg', frame)[1].tobytes()

        except BlockingIOError as e:  # 这里UDP传输有错误是正常的，但是影响不大，所以下面直接pass掉
            pass
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cv2.destroyAllWindows()


t1 = threading.Thread(target=revecive)
t1.start()


async def recv_msg(websocket):

    # print(type(data))
    USERS.append(websocket)
    print('已连接...', USERS, len(USERS))
    while True:
        try:
            # await USERS[len(USERS) - 1].send(data)
            await websocket.send(data)
        # except websockets.ConnectionClosedError as e:
        except Exception as e:
            print('视频转发：寄！')
            print(e.args)
            print('即将重启')
            time.sleep(0.5)
            USERS.clear()
            break
        finally:
            pass


async def main_logic(websocket):
    await recv_msg(websocket)


def MAIN():
    try:
        while True:
            pass
    except Exception as e:
        print("寄掉了！！")
        print(e.args)
        print("即将开始重启")
        time.sleep(3)
        threading.Thread(target=MAIN).start()


threading.Thread(target=MAIN).start()


start_server = websockets.serve(main_logic, 'localhost', ws_port)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
